
type storageType = 'session' | 'local'
//联合类型
export default function useStorage() {
  /**
   * @method 读取缓存
   * @param type sessionStorage | localStorage
   * @param key 要读取的key
   * @returns 根据key返回本地数据
   */
  function getStorage<D = any>(type: storageType, key: string): D {
    let _data: any = {}
    _data = type === 'session' ? sessionStorage.getItem(key) : localStorage.getItem(key)
    return JSON.parse(_data)
  }
 
  /**
   * @method 设置缓存
   * @param type sessionStorage | localStorage
   * @param key 要设置的key
   * @param data 要设置的值
   */
  function setStorage<D = any>(type: storageType, key: string, data: D) {
    const _data = JSON.stringify(data)
    type === 'session' ? sessionStorage.setItem(key, _data) : localStorage.setItem(key, _data)
  }
 
  /**
   * @method 移除缓存
   * @param type sessionStorage | localStorage
   * @param key 要移除的key
   */
  function removeStorage(type: storageType, key: string) {
    type === 'session' ? sessionStorage.removeItem(key) : localStorage.removeItem(key)
  }
 
  return {
    getStorage,
    setStorage,
    removeStorage,
  }
}

 